package httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import java.io.IOException;

public class HttpClientTest
{
    @Test
    public void doGetTest()
    {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //创建get请求
        HttpGet httpGet = new HttpGet("http://www.rczs.com:8082/GeoResources/terrain_tiles/layer.json");

        //响应模型
        CloseableHttpResponse response = null;

        try
        {
            //客户端发送get请求
            response = httpClient.execute(httpGet);
            //从响应中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为：" + response.getStatusLine());
            if (responseEntity != null)
            {
                System.out.println("响应内容长度为：" + responseEntity.getContentLength());
                System.out.println("响应内容为："+ EntityUtils.toString(responseEntity));
            }
        }

        catch (ClientProtocolException e)
        {
            e.printStackTrace();
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }finally
        {
            try
            {
                //释放资源
                if (httpClient != null)
                {
                    httpClient.close();
                }
                if (response != null)
                {
                    response.close();
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}
